package com.ugoodtech.mdcc.web.controller;

import com.mysema.query.BooleanBuilder;
import com.ugoodtech.mdcc.core.domain.*;
import com.ugoodtech.mdcc.core.exception.VStarException;
import com.ugoodtech.mdcc.core.repository.ChinaDistrictRepository;
import com.ugoodtech.mdcc.core.repository.ModuleAuthorityRepository;
import com.ugoodtech.mdcc.core.repository.RoleRepository;
import com.ugoodtech.mdcc.core.service.NationService;
import com.ugoodtech.mdcc.core.service.RoleService;
import com.ugoodtech.mdcc.core.utils.BaseUtil;
import com.ugoodtech.mdcc.web.dto.JsonResponse;
import com.ugoodtech.mdcc.web.dto.LabelValue;
import com.ugoodtech.mdcc.web.dto.RoleReponse;
import com.ugoodtech.mdcc.web.service.UserService;
import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;


@Api(description = "角色管理")
@Controller
@RequestMapping("/role")
public class RoleController extends BaseController {

    @Autowired
    private RoleService roleService;

    @Autowired
    private UserService userService;

    @Autowired
    private RoleRepository roleRepository;

    @Autowired
    private ChinaDistrictRepository chinaDistrictRepository;

    @Autowired
    private ModuleAuthorityRepository moduleAuthorityRepository;

    @Autowired
    private NationService nationService;

    @ApiOperation("角色列表")
    @ApiResponses({
            @ApiResponse(code = 200, message = "data", response = User.class)
    })
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页数", required = false, paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "size", value = "每页条数", required = false, paramType = "query", dataType = "int"),
    })
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse getAllRole(Pageable pageable) {
        isUserLogin();
        Page<Role> roles = roleService.queryRole(pageable, null);
        return JsonResponse.successResponseWithPageData(roles);
    }

    @ApiOperation("添加角色")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    public JsonResponse add(
            @ApiParam("角色名称") @RequestParam("name") String name,
            @ApiParam("角色名称") @RequestParam("desc") String desc,
            @ApiParam("角色名称") @RequestParam Long[] functionIds) throws VStarException {
        isUserLogin();
        Set<ModuleAuthority> moduleAuthorities = BaseUtil.getModelSet(moduleAuthorityRepository, functionIds);
        roleService.createRole(name, moduleAuthorities, desc);
        return JsonResponse.successResponse();
    }

    @ApiOperation("编辑角色")
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    @ResponseBody
    public JsonResponse edit(
            @ApiParam("角色id") @RequestParam("roleId") Long roleId,
            @ApiParam("角色名称") @RequestParam("name") String name,
            @ApiParam("描述") @RequestParam("desc") String desc,
            @ApiParam("菜单权限") @RequestParam Long[] functionIds) throws VStarException {
        isUserLogin();
        Role role = roleRepository.findOne(roleId);
        Set<ModuleAuthority> moduleAuthorities = BaseUtil.getModelSet(moduleAuthorityRepository, functionIds);
        role.setName(name);
        role.setDescription(desc);
        role.setAuthorities(moduleAuthorities);
        roleRepository.save(role);
        return JsonResponse.successResponse();
    }

    @ApiOperation("激活禁用角色")
    @RequestMapping(value = "/changeStatus", method = RequestMethod.POST)
    @ResponseBody
    public JsonResponse changeStatus(
            @ApiParam("roleId") @RequestParam("roleId") Long roleId,
            @ApiParam("激活:true/禁用:false") @RequestParam("enabled") boolean enabled
    ) throws VStarException {
        isUserLogin();
        Role role = roleRepository.findOne(roleId);
        role.setEnabled(enabled);
        roleRepository.save(role);
        return JsonResponse.successResponse();
    }

    @ApiOperation("删除角色")
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    public JsonResponse delete(
            @ApiParam("角色id") @RequestParam("roleId") Long roleId
    ) throws VStarException {
        isUserLogin();
        Role role = roleRepository.findOne(roleId);
        role.setDeleted(true);
        roleRepository.save(role);
        return JsonResponse.successResponse();
    }


    @ApiOperation("获取权限列表")
    @ApiResponses({
            @ApiResponse(code = 200, message = "data", response = User.class)
    })
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页数", required = false, paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "size", value = "每页条数", required = false, paramType = "query", dataType = "int"),
    })
    @RequestMapping(value = "/authorityList", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse authorityList(Pageable pageable) {
        isUserLogin();
        QModuleAuthority qModuleAuthority = QModuleAuthority.moduleAuthority;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qModuleAuthority.deleted.eq(false));
        builder.and(qModuleAuthority.enabled.eq(true));
        Iterable<ModuleAuthority> moduleAuthorities = moduleAuthorityRepository.findAll(builder);
        return JsonResponse.successResponseWithData(moduleAuthorities);
    }


    @ApiOperation("角色下拉框")
    @ApiResponses({
            @ApiResponse(code = 200, message = "data", response = User.class)
    })
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页数", required = false, paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "size", value = "每页条数", required = false, paramType = "query", dataType = "int"),
    })
    @RequestMapping(value = "/comboList", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse comboList(Pageable pageable) {
        isUserLogin();
        QRole qRole = QRole.role;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qRole.deleted.eq(false));
        Sort sort = new Sort(Sort.Direction.DESC, "creationTime");
        pageable = new PageRequest(pageable.getPageNumber(), pageable.getPageSize(), sort);
        Page<Role> roles = roleRepository.findAll(builder, pageable);
        List<RoleReponse> roleReponses = new ArrayList<>();
        for (Role role : roles) {
            RoleReponse roleReponse = new RoleReponse();
            if (role.isEnabled() == false) {
                roleReponse.setShow(false);
            }
            roleReponse.setId(role.getId());
            roleReponse.setDescription(role.getDescription());
            roleReponse.setName(role.getName());
            roleReponses.add(roleReponse);
        }
        Page<RoleReponse> reponsePage = new PageImpl(roleReponses, pageable, roles.getTotalElements());
        return JsonResponse.successResponseWithPageData(reponsePage);
    }

    @ApiOperation("权限多选框")
    @RequestMapping(value = "/authoritycomboList", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse authoritycomboList() {
        isUserLogin();
        QModuleAuthority qModuleAuthority = QModuleAuthority.moduleAuthority;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qModuleAuthority.deleted.eq(false));
        builder.and(qModuleAuthority.enabled.eq(true));
        Iterable<ModuleAuthority> moduleAuthorities = moduleAuthorityRepository.findAll(builder);
        List<LabelValue> comboData = new ArrayList<>();
        for (ModuleAuthority moduleAuthority : moduleAuthorities) {
            LabelValue labelValue = new LabelValue(moduleAuthority.getDescription(), moduleAuthority.getId() + "");
            comboData.add(labelValue);
        }
        return JsonResponse.successResponseWithData(comboData);
    }


}
